package com.imooc.mall.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class WebLogAspect {
    // 记录日志
    private final Logger log = LoggerFactory.getLogger(WebLogAspect.class);
    // 切入点。对哪些请求进行拦截
    @Pointcut("execution(public * com.imooc.mall.controller.*.*(..)))")
    public void weblog() {

    }

    /**
     * 请求前拦截
     * @param joinPoint joinPoint
     */
    @Before("weblog()")
    public void doBefore(JoinPoint joinPoint) { // joinPoint 得到类的方法的信息
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("[ URL : " + request.getRequestURL() + "]");
        log.info("[ HTTP_METHOD : " + request.getMethod() + "]");
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 处理完请求返回内容
     * @param res res
     */
    @AfterReturning(returning = "res", pointcut = "weblog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        log.info("RESPONSE : " + new ObjectMapper().writeValueAsString(res));
    }
}
